from flask import session, render_template, current_app, request, g
from flask.json import jsonify

from . import index_blu
from ... import constants
from ...models import User, News, Category
from ...utils.common import user_login_data
from ...utils.response_code import RET


@index_blu.route('/')
@user_login_data
def index():
    # 获取用户信息
    user = g.user
    # 获取点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 定义空列表，存每条新闻的字典
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 获取新闻分类
    categories = Category.query.all()
    category_li = []
    for category in categories:
        category_li.append(category.to_dict())
    data = {
        'user': user.to_dict() if user else None,
        'news_dict_li': news_dict_li,
        'category_li': category_li
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/news_list')
def news_list():
    # 1.获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    # 2.检验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)

    # 3.查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')

    # 取当前也数据
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        'total_page': total_page,
        'current_page': current_page,
        'news_dict_li': news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg='ok', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')